import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
// import qs from 'qs'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error && error.stack.indexOf('timeout') > -1) {
    notification.error({
      message: '警告',
      description: '网络请求超时'
    })
  }
  const data = error.response.data
  // 从 localstorage 获取 token
  const token = storage.get(ACCESS_TOKEN)
  if (data.code === 403) {
    notification.error({
      message: '错误',
      description: data.message
    })
    if (token) {
      store.dispatch('Logout').then(() => {
        setTimeout(() => {
          window.location.reload()
        }, 1500)
      })
    }
  }
  if (data.code === 405) {
    notification.error({
      message: '错误',
      description: data.message
    })
  }
  if (error.response) {
    const data = error.response.data
    console.log('请求网络返回数据为')
    console.log(data)
    // 从 localstorage 获取 token
    if (error.response.data.code === 403) {
      notification.error({
        message: '警告',
        description: data.message
      })
    }
    if (error.response.status === 404) {
      notification.error({
        message: '错误',
        description: '404！文件丢失或权限不足'
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  const data = response.data
  if (data.code === 403) {
    notification.error({
      message: '错误',
      description: data.message
    })
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    })
  }
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
